package x.ovo.wechat.bot.plugin;

import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import x.ovo.wechat.bot.core.event.Event;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.event.ExceptionEvent;
import x.ovo.wechat.bot.core.event.SystemEvent;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.util.Map;

@Slf4j
@SuppressWarnings("rawtypes")
public class PushListener extends EventListener<Event<Object>, Object> {

    private final Map<String, ?> config = this.plugin.getConfig();
    private final OkHttpClient client = (OkHttpClient) this.context.getHttpEngine().getRawEngine();

    public PushListener(Plugin plugin) {
        super(plugin);
    }

    @Override
    public boolean support(@NonNull Event event, Object source) {
        return event instanceof SystemEvent || event instanceof ExceptionEvent;
    }

    @SneakyThrows
    @Override
    public boolean onEvent(@NonNull Event event, Object source) {
        // 处理异常事件
        if (event instanceof ExceptionEvent && source instanceof Throwable e) {
            String error = LogUtil.printError(e);
            DingDingPush.push(this.config, this.client, "异常消息", error);
        } else if (event instanceof SystemEvent se) {
            DingDingPush.push(this.config, this.client, "系统消息", se.getSource());
        }
        return true;
    }

    @Override
    public boolean executeNext() {
        return false;
    }
}
